import React from 'react'
import { connect } from 'react-redux'
import { messages, getDefaultPermissionSetOfBook, getDefaultPermissionCompany } from "share/common"
import { Button, Row, Form, Col, Spin, Popconfirm, Dropdown, Icon, Menu, Radio } from 'antd';
const RadioGroup = Radio.Group;
import SlideFrame from  'components/slide-frame'
import AdvancedTable from 'components/advanced-table'
const SimpleTable = AdvancedTable.SimpleTable;
import errorMessage from "share/errorMessage";
import "styles/setting/workflow-matrix/matrix-list.scss"
import menuRoute from 'routes/menuRoute'
import  NewMatrix from 'containers/setting/workflow-matrix/new-matrix'
import workflowMatrixService from 'containers/setting/workflow-matrix/workflow-matrix.service';
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14, offset: 1 },
};
const options = [
  { label: messages('common.all')/*全部*/, value: 'ALL' },
  { label: messages('request-4.key584')/*账套*/, value: 'SET_OF_BOOK' },
  { label: messages('request-4.key12')/*公司*/, value: 'COMPANY' },
];
class MatrixList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      tableConfig: {
        columns: [
          {
            dataIndex: 'levelCode', title: messages('request-4.key554')/*层级*/,
            width: 120,
            render: (text) => {
              return <span>
              {text === 'SET_OF_BOOK' ? messages('request-4.key584')/*账套*/ :messages('request-4.key12')/*公司*/}</span>
            }
          }, {
            width: 260,
            dataIndex: 'levelOrgName', title: messages('request-4.key555')/*所属组织*/,
            render: text => text || '-',
          }, {
            width: 260,
            dataIndex: 'enabled', title: messages('request-4.key585')/*适用公司*/,
            render: (text, record) => {
              return (record.visibleCompanyScope === 1 && record.levelCode === 'SET_OF_BOOK') ?  messages('request-4.key443')/*通用*/
                : this.getCompanyNames(record.visibleCompanyRelation) || record.levelOrgName
            }
          }, {
            dataIndex: 'name', title: messages('request-4.key586')/*审批矩阵名称*/,
          }, {
            title: messages('common.operation')/*操作*/, key: 'operation', render: (text, record) => (
           <span>
            <a onClick={(e) => this.editItem(e, record)}>{messages('request-4.key579')/*条件维度*/}</a>
            <span className="ant-divider"/>
            <a onClick={e => this.matrixDetail(e, record)}>{messages('request-4.key580')/*矩阵明细*/}</a>
          </span>)
          },
        ],
        // searchForm: [
        //   {
        //     id: 'levelCode',
        //     initialValue: 'ALL',
        //     label: messages('request-4.key554')/*层级*/,
        //     component: <RadioGroup options={options} initialValue="ALL"/>,
        //     tagParser: value => this.getLevelTypeValue(value),
        //     dataIndex: 'levelCode',
        //   }, {
        //     id: 'levelOrgId',
        //     dataIndex: 'levelOrgName',
        //     label: messages('request-4.key555')/*所属组织*/,
        //     parser: value => ({ levelOrgId: value ? value.rangeValue.id : null }),
        //     tagParser: value => value && value.rangeValue.name,
        //     component: <Priority
        //       style={{ marginLeft: 0 }}
        //       formItemLayout={formItemLayout}
        //       top='TENANT'
        //       onlyCompany
        //       showCompanyComponent={false}
        //       showCompany
        //       companyProps={{
        //         single: true
        //       }}
        //     />,
        //   }
        // ],
        defaultValue: {},
        topPermission: ''
      }
    }
  }


  getLevelTypeValue(type) {
    let text = messages('common.all')/*全部*/;
    switch(type) {
      case 'TENANT':
        text = messages('request-4.key553')/*租户*/;
        break;
      case 'COMPANY':
        text = messages('request-4.key12')/*公司*/;
        break;
    }
    return text;
  }

  editItem = (e,item) => {
    e.stopPropagation();
    this.context.router.push(menuRoute.getRouteItem('approval-matrix-detail').url
      .replace(':id', item.approvalMatrixId).replace(':name', item.name)
      .replace(':tab','condition')
      .replace(':setOfBooksId', item.setOfBooksId));
  };

  matrixDetail = (e,item) => {
    e.stopPropagation();
    this.context.router.push(menuRoute.getRouteItem('approval-matrix-detail').url
      .replace(':id', item.approvalMatrixId).replace(':name', item.name)
      .replace(':tab', 'detail')
      .replace(':setOfBooksId', item.setOfBooksId));
  };

  service = (page, size, searchParams) => {
    return workflowMatrixService.getWorkflowMatrixList({ page, size, ...searchParams })
  }

  afterCloseSlideFrame = flag => {
    if (flag) {
      this.advancedTableRef.getList()
    }
  }

  getCompanyNames = list => {
    let companyNameList = (list || []).map(item => {
      return item.name
    });
    return companyNameList.join('、')
  };

  componentDidUpdate() {
    let { permissionLoading } = this.props.currentMenuPermission;
    let { topPermission, defaultValue } =this.state;
    if (!permissionLoading && !topPermission) {
      let currentMenuPermission = this.props.currentMenuPermission
      if (currentMenuPermission.currentMenuPermission && currentMenuPermission.currentMenuPermission.authPolicyCompDTO) {
        let authPolicyCompDTO = currentMenuPermission.currentMenuPermission.authPolicyCompDTO;
        let isHasSetOfBook = authPolicyCompDTO.setOfBooksIds && !!authPolicyCompDTO.setOfBooksIds.length;
        (isHasSetOfBook ? getDefaultPermissionSetOfBook() : getDefaultPermissionCompany())
          .then(res => {
            let resDate = isHasSetOfBook ? res.data : res;
            topPermission = isHasSetOfBook ? 'SET_OF_BOOK' : 'COMPANY'
            defaultValue = {
              range: topPermission,
              'levelOrgName': isHasSetOfBook ? resDate.defaultSetOfBooksName : resDate.name,
              'levelOrgId': isHasSetOfBook ? resDate.defaultSetOfBooksId : resDate.id,
              rangeValue: [{
                [isHasSetOfBook ? 'setOfBooksName' : 'name']: isHasSetOfBook ? resDate.defaultSetOfBooksName : resDate.name,
                [isHasSetOfBook ? 'setOfBooksId' : 'id']: isHasSetOfBook ? resDate.defaultSetOfBooksId : resDate.id
              }]
            }
            this.setState({
              loading: false,
              topPermission,
              defaultValue
            });
          })
      }
    }
  }

  componentDidMount() {
  }

  handleCreate = (title, record) => {
    let { topPermission, defaultValue } = this.state;
    // let  isHasSetOfBook =  ? 'SET_OF_BOOK' : 'COMPANY'
    SlideFrame.open({
      title: title || messages('request-4.key587')/*新建矩阵*/,
      content: NewMatrix,
      afterClose: this.afterCloseSlideFrame,
      width: '800px',
      params: {
        topPermission,
        defaultValue: title ? {
            levelOrgName: record.levelOrgName,
            range: record.levelCode,
            levelOrgId: record.levelOrgId,
            rangeValue: [{
              [topPermission === 'SET_OF_BOOK' ? 'setOfBooksName' : 'name']: record.levelOrgName,
              [topPermission === 'SET_OF_BOOK' ? 'setOfBooksId' : 'id']: record.levelOrgId
            }]
          } : defaultValue,
        id: record && record.approvalMatrixId
      }
    }, this);
  }

  render() {
    const { tableConfig,  loading, } = this.state;
    return (
      <Spin spinning={loading}>
        <div className='workflow-matrix full-height-page'>
          <SimpleTable
            onRef={ref => this.advancedTableRef = ref}
            {...tableConfig}
            onRow={record => ({
              onClick: () => this.handleCreate(messages('request-4.key588')/*编辑矩阵*/, record)
            })}
            rowKey="approvalMatrixId"
            onGetDataError={e => errorMessage(e.response)}
            service={this.service}
          >
            <Row type="flex" className="handle-row" justify="space-between" align="middle">
              <Col span={12}>
                <Button
                  type="primary"
                  onClick={() => this.handleCreate()}>
                  {messages('common.create')/*新建*/}
                </Button>
              </Col>
            </Row>
          </SimpleTable>
        </div>
      </Spin>
    )
  }

}
MatrixList.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode,
    company: state.login.company,
    language: state.main.language,
    currentMenuPermission: state.main.currentMenuPermission,
  }
}

const wrappedMatrixList = Form.create()(MatrixList);

export default connect(mapStateToProps)(wrappedMatrixList)